﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EasyMvc.Utility;
using System.Web;

namespace EasyMvc.Core
{
    public class HttpContextBase
    {

        public virtual string KeyPrefix
        {
            get
            {
                return Fetch.ServerDomain + "_HttpContext_";
            }
        }

        public virtual string UserName
        {
            get
            {
                return HttpUtility.UrlDecode(Cookie.GetValue(KeyPrefix + "UserName"));
            }
            set
            {
                Cookie.Save(KeyPrefix + "UserName", HttpUtility.UrlEncode(value), 1);
            }
        }

        public virtual int UserId
        {
            get
            {
                return Cookie.GetValue(KeyPrefix + "UserId").ToInt();
            }
            set
            {
                Cookie.Save(KeyPrefix + "UserId", value.ToString(), 1);
            }
        }

        public virtual Guid UserToken
        {
            get
            {
                return Cookie.GetValue(KeyPrefix + "UserToken").ToGuid();
            }
            set
            {
                Cookie.Save(KeyPrefix + "UserToken", value.ToString(), 1);
            }
        }

        public virtual string VerifyCode
        {
            get
            {
                return Encrypt.Decode(Cookie.GetValue(KeyPrefix + "VerifyCode"));
            }
            set
            {
                Cookie.Save(KeyPrefix + "VerifyCode", Encrypt.Encode(value), 1);
            }
        }

        public virtual int LoginErrorTimes
        {
            get
            {
                return Cookie.GetValue(KeyPrefix + "LoginErrorTimes").ToInt();
            }
            set
            {
                Cookie.Save(KeyPrefix + "LoginErrorTimes", value.ToString(), 1);
            }
        }

        public virtual bool IsNeedVerifyCode
        {
            get
            {
                return LoginErrorTimes > 1;
            }
        }

        /// <summary>
        /// Clear the user cookie
        /// </summary>
        public virtual void RemoveUserCookie()
        {
            Cookie.Remove(KeyPrefix + "UserId");
            Cookie.Remove(KeyPrefix + "UserName");
            Cookie.Remove(KeyPrefix + "UserToken");

        }
    }
}
